<template>
  <div class="editor-html">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{ height: height + 'px', 'overflow-y': 'hidden' }"
      :model-value="modelValue"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="onChange"
    />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { defineProps, defineEmits } from "vue";

// 定义 props
//eslint-disable-next-line no-unused-vars
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  height: {
    type: Number,
    default: 500,
  },
});

// 定义 emits
const emit = defineEmits(["update:modelValue"]);

// 编辑器模式
const mode = ref("default");

// 编辑器实例
const editorRef = shallowRef();

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [], // 排除不需要的菜单项
  toolbarKeys: [
    "headerSelect", // 标题
    "bold", // 加粗
    "italic", // 斜体
    "underline", // 下划线
    "indent", // 缩进
    "lineHeight", // 行高
    "justifyLeft", // 左对齐
    "justifyCenter", // 居中对齐
    "justifyRight", // 右对齐
    "justifyJustify", // 两端对齐
    "blockquote", // 引用
    "code", // 行内代码
    "codeBlock", // 代码块
    "undo", // 撤销
    "redo", // 重做
    "color", // 颜色
    "indent", // 缩进
    "fullScreen", // 全屏
  ],
};

// 编辑器配置
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 3 * 1024 * 1024, // 限制图片大小为 3MB
      server: "/api/upload/image", // 后端上传接口
      customInsert(res, insertFn) {
        insertFn(res.data.url, "", "");
      },
    },
  },
};

// 编辑器内容变化时触发
const onChange = (editor) => {
  emit("update:modelValue", editor.getHtml());
};

// 组件销毁时，销毁编辑器实例
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 编辑器创建时触发
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例
};
</script>

<style lang="scss">
.editor-html {
  border: 1px solid #ddd;
}
</style>